package com.example.shaojun.fragmentliefcycle;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class BtTest extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "BtTest";
    BluetoothAdapter bAdapter;//声明蓝牙适配器
    EditText nameView;//声明edittext
    String blueName;//声明用户输入的蓝牙设备名称变量
    TextView showRssi;//声明textview用于显示信号强度信息
    Boolean bFind = false;
    ScrollView scrollView;
    TextView scrollText;

    StringBuilder btInfo;

    Button buttonOpen;
    Button buttonClose;
    Button buttonRssi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bt_test);
        bAdapter = BluetoothAdapter.getDefaultAdapter();//获取蓝牙适配器
        //设置过滤器，过滤因远程蓝牙设备被找到而发送的广播 BluetoothDevice.ACTION_FOUND
        IntentFilter iFilter=new IntentFilter();
        iFilter.addAction(BluetoothDevice.ACTION_FOUND);
        iFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //设置广播接收器和安装过滤器
        registerReceiver(new foundReceiver(), iFilter);
        //获取控件对象
        nameView = (EditText) findViewById(R.id.bluetoothName);
        showRssi = (TextView) findViewById(R.id.showRssi);

        buttonOpen = findViewById(R.id.open);
        buttonClose = findViewById(R.id.close);
        buttonClose = findViewById(R.id.show);
        buttonOpen.setOnClickListener(this);

        scrollText = findViewById(R.id.scroll_text);
        btInfo = new StringBuilder();
    }

    @Override
    public void onClick(View view) {
        Log.d(TAG,"viewId:" + view.getId());
        switch (view.getId()){
            case R.id.open:
                open(view);
                break;

            case R.id.close:
                close(view);
                break;

            case R.id.show:
                show(view);
                break;
            default:
                Log.d(TAG,"default");
                break;
        }
    }
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }

    /**
     * 打开蓝牙
     * @param v
     */
    public void open(View v) {
        if(!bAdapter.isEnabled()){
            bAdapter.enable();
            Toast.makeText(getApplicationContext(), "蓝牙打开成功", Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getApplicationContext(), "蓝牙已经打开", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 关闭蓝牙
     * @param v
     */
    public void close(View v) {
        if(bAdapter.isEnabled()){
            bAdapter.disable();
            Toast.makeText(getApplicationContext(), "蓝牙关闭成功", Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getApplicationContext(), "蓝牙已经关闭", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 搜索远程蓝牙设备，获取editview的值
     * @param v
     */
    public void show(View v) {
        if(bAdapter.isEnabled()){
            blueName = nameView.getText().toString().trim();
            if(!bAdapter.isDiscovering()) {
                showRssi.setText("正在搜索...");
                scrollText.setText("");
                bAdapter.startDiscovery();
            }
            else {
                Toast.makeText(getApplicationContext(), "正在搜索", Toast.LENGTH_LONG).show();;
            }
        }else{
            Toast.makeText(getApplicationContext(), "蓝牙未打开", Toast.LENGTH_LONG).show();;
        }
    }

    /**
     * 内部类：当找到一个远程蓝牙设备时执行的广播接收者
     * @author Administrator
     *
     */
    class foundReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获取此时找到的远程设备对象
                String name = device.getName();
                String name1 = intent.getExtras().getString(BluetoothDevice.EXTRA_NAME);
                short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
                btInfo.append(name+"\n");
                btInfo.append(name1 + "\n");
                btInfo.append(device.getAddress()+ " rssi:" + rssi + "\n");
                scrollText.setText(btInfo.toString());
                if (blueName.equals(name)) {//判断远程设备是否与用户目标设备相同
                    bFind = true;
                    showRssi.setText(device.getName() + ":" + rssi);
                    bAdapter.cancelDiscovery();//关闭搜索
                } else {
                    showRssi.setText("已找到:" + name + " Rssi:"+ rssi +"  ->正在搜寻设备“" + blueName + "”");
                }
            }
            else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                if(!bFind){
                    showRssi.setText("未发现设备“" + blueName + "”");
                }
            }
        }

    }
}
